package org.linlinjava.litemall.admin.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.dto.VendorAddressDTO;
import org.linlinjava.litemall.core.dto.VendorAllinone;
import org.linlinjava.litemall.core.service.AdminVendorService;
import org.linlinjava.litemall.admin.service.LogHelper;
import org.linlinjava.litemall.admin.util.CommonUtil;
import org.linlinjava.litemall.core.vo.VendorRegVo;
import org.linlinjava.litemall.core.captcha.service.CaptchaCodeManager;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.Vendor;
import org.linlinjava.litemall.db.domain.VendorEmployee;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static org.linlinjava.litemall.core.util.AdminResponseCode.*;

@Slf4j
@RestController
@RequestMapping("/admin/vendor")
@Validated
public class AdminVendorController {

    @Autowired
    private AdminVendorService vendorService;
    @Autowired
    private LitemallAdminService adminService;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private LogHelper logHelper;

    @RequiresPermissions("admin:vendor:list")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String vendorCode, String vendorName, @RequestParam(defaultValue = "0") Integer status,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<Vendor> vendorList = vendorService.query(vendorCode, vendorName, status, page, limit, sort, order);
        return ResponseUtil.okList(vendorList);
    }

    private Object validate(Vendor vendor) {
        String name = vendor.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:vendor:create")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody VendorAllinone vendor) {
        Object error = validate(vendor.getVendor());
        if (error != null) {
            return error;
        }
        if(!adminService.findAdmin(vendor.getRegVo().getUsername()).isEmpty()) {
            return ResponseUtil.fail(401, vendor.getRegVo().getUsername() + "已被注册");
        }
        vendorService.create(vendor);
        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:read")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Long id) {
        Vendor vendor = vendorService.findById(id);
        return ResponseUtil.ok(vendor);
    }


    @PostMapping("/register")
    public Object register(@RequestBody VendorRegVo regVo) {
        boolean valid = regVo.isValid();
        if (!valid) {
            return ResponseUtil.badArgument();
        }

        if(!regVo.getCaptcha().equals(CaptchaCodeManager.getCachedCaptcha(regVo.getPhone()))) {
            return ResponseUtil.fail(401, "验证码不正确");
        }

        if(!adminService.findAdmin(regVo.getUsername()).isEmpty()) {
            return ResponseUtil.fail(401, regVo.getUsername() + "已被注册");
        }
        return ResponseUtil.ok(vendorService.doReg(regVo));
    }

    /**
     * 发送验证码
     * @param body
     * @return
     */
    @PostMapping("/regCaptcha")
    public Object registerCaptcha(@RequestBody String body) {
        String phoneNumber = JacksonUtil.parseString(body, "mobile");
        if (StringUtils.isEmpty(phoneNumber)) {
            return ResponseUtil.badArgument();
        }
        if (!RegexUtil.isMobileExact(phoneNumber)) {
            return ResponseUtil.badArgumentValue();
        }

        if (!notifyService.isSmsEnable()) {
            return ResponseUtil.fail(701, "后台验证码服务不支持");
        }
        String code = CharUtil.getRandomNumNo4(6);
        notifyService.notifySmsTemplate(phoneNumber, NotifyType.CAPTCHA, new String[]{code});

        log.info("captcha:{}", code);

        boolean successful = CaptchaCodeManager.addToCache(phoneNumber, code);
        if (!successful) {
            return ResponseUtil.fail(702, "验证码未超时1分钟，不能发送");
        }

        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:vendor:myvendor")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "当前商户信息")
    @GetMapping("/myVendor")
    public Object myVendor() {
        return read(CommonUtil.getVendorId());
    }

    @RequiresPermissions("admin:vendor:editMyVendor")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "编辑当前商户")
    @PostMapping("/editMyVendor")
    public Object editMyVendor(@RequestBody Vendor vendor) {
        vendor.setId(CommonUtil.getVendorId());
        vendor.setStatus(-1);
        return update(vendor);
    }

    @RequiresPermissions("admin:vendor:update")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody Vendor vendor) {
        Object error = validate(vendor);
        if (error != null) {
            return error;
        }
        if (vendorService.updateById(vendor) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:approve")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺审核"}, button = "审核")
    @PostMapping("/approve")
    public Object approve(@RequestBody Vendor vendor) {
        Vendor v = new Vendor();
        v.setId(vendor.getId());
        v.setStatus(vendor.getStatus());
        v.setMemo(vendor.getMemo());
        if (vendorService.approve(v) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(vendor);
    }

    @RequiresPermissions("admin:vendor:delete")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody Vendor vendor) {
        Long id = vendor.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        vendorService.deleteById(id);
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:vendor:getEmployees")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "查看")
    @GetMapping("/employees")
    public Object getEmployees(@NotNull Long vendorId) {
        List<VendorEmployee> employees = vendorService.getEmployees(vendorId);
        return ResponseUtil.okList(employees);
    }
    @RequiresPermissions("admin:vendor:deleteEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "删除")
    @PostMapping("/deleteEmployee")
    public Object deleteEmployee(@RequestBody VendorEmployee employee) {
        Long id = employee.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        vendorService.deleteEmployeeById(id);

        return ResponseUtil.ok();
    }
    @RequiresPermissions("admin:vendor:publishEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "新增")
    @PostMapping("/publishEmployee")
    public Object publishEmployee(@RequestBody VendorEmployee employee) {
        Object error = validateEmployee(employee, false);
        if (error != null) {
            return error;
        }

        List<LitemallAdmin> adminList = adminService.findAdmin(employee.getUsername());
        if (adminList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "此登陆账号已经存在");
        }

        if (!RegexUtil.isUsername(employee.getUsername())) {
            return ResponseUtil.fail(ADMIN_INVALID_NAME, "登陆账号不符合规定");
        }

        if(StringUtils.isEmpty(employee.getPassword())){
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD, "密码不能为空");
        }

        vendorService.addEmployee(employee);
        logHelper.logAuthSucceed("添加商铺管理员", employee.getUsername());

        return ResponseUtil.ok(employee);
    }

    @RequiresPermissions("admin:vendor:editEmployee")
    @RequiresPermissionsDesc(menu = {"商铺管理", "店员管理"}, button = "编辑")
    @PostMapping("/editEmployee")
    public Object editEmployee(@RequestBody VendorEmployee employee) {
        Object error = validateEmployee(employee, true);
        if (error != null) {
            return error;
        }
        employee.setUsername(null);
        if (vendorService.updateEmployeeById(employee) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(employee);
    }

    @RequiresPermissions("admin:vendor:getAddr")
    @RequiresPermissionsDesc(menu = {"商铺管理", "商铺管理"}, button = "查询地址")
    @GetMapping("/getAddr")
    public Object getAddr() {
        Vendor vendor = vendorService.getById(CommonUtil.getVendorId());
        if(null != vendor) {
            return ResponseUtil.ok(VendorAddressDTO.fromVendor(vendor));
        } else {
            return ResponseUtil.fail(404, "未找到对应商铺");
        }
    }


    private Object validateEmployee(VendorEmployee employee, boolean isUpdate) {
        if (StringUtils.isEmpty(employee.getName())) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isEmpty(employee.getUsername())) {
            return ResponseUtil.badArgument();
        }
        if(!isUpdate && !adminService.findAdmin(employee.getUsername()).isEmpty()) {
            return ResponseUtil.fail(401, employee.getUsername() + "已被注册");
        }
        return null;
    }
}
